package com.lhx.tree.bilibili;

import com.lhx.tree.TreeNode;

import java.util.Stack;

//迭代实现
public class tree_test {
    public static void preorder(TreeNode root) {
        if(root != null) {
            Stack<TreeNode> stack = new Stack<TreeNode>();
            stack.add(root);
            while(!stack.isEmpty()) {
                root = stack.pop();
                if(root != null) {
                    System.out.println(root.val);
                    stack.push(root.right);
                    stack.push(root.left);
                }
            }
        }
    }

    public static void midorder(TreeNode root) {
        if(root != null) {
            Stack<TreeNode> stack = new Stack<TreeNode>();

            while(!stack.isEmpty() || root != null) {
                if(root != null) {
                    stack.push(root);
                    root = root.left;
                } else {
                    root = stack.pop();
                    System.out.println(root.val);
                    root = root.right;
                }
            }
        }
    }

    public static void main(String[] args) {
        TreeNode node7 = new TreeNode(7,null,null);
        TreeNode node6 = new TreeNode(6,null,null);
        TreeNode node5 = new TreeNode(5,node6,node7);
        TreeNode node4 = new TreeNode(4,null,null);
        TreeNode node3 = new TreeNode(3,null,null);
        TreeNode node2 = new TreeNode(2,node4,node5);
        TreeNode node1 = new TreeNode(1,node2,node3);
        preorder(node1);

        midorder(node1);
    }
}
